package cn.uniqueinfo.dp.controller;

import cn.uniqueinfo.dp.controller.base.BaseController;
import cn.uniqueinfo.dp.service.IRoleMenuService;
import cn.uniqueinfo.dp.util.ResultUtil;
import cn.uniqueinfo.dp.vo.Result;
import cn.uniqueinfo.dp.vo.RoleMenuVO;
import cn.uniqueinfo.dp.vo.SaveItem;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-02-13 11:51:24
 * @description:角色菜单对应表
 */
@Slf4j
@Controller
@RequestMapping(value = "/rolemenu")
public class RoleMenuController extends BaseController<RoleMenuVO> {
    private IRoleMenuService service;

    public RoleMenuController(IRoleMenuService service) {
        this.service = service;
        this.baseService = service;
        this.ctlName = "rolemenu";
        this.tipName = "角色菜单对应表";
    }

    /** 根据角色id来获取 */
    @GetMapping(value = "/getMenuItems")
    @ResponseBody
    public List<RoleMenuVO> getMenuItems(@RequestParam(value = "rid") Long roleId) {
        return this.service.findByRoleId(roleId);
    }

    /** 批量插入 */
    @PostMapping(value = "/bi")
    @ResponseBody
    public Result patchInsert(
            @RequestParam(value = "rid") Long roleId, @RequestParam(value = "mids") String mids) {

        if (mids == null || mids == "") {
            return ResultUtil.fail();
        }

        try {
            this.service.deleteByRoleId(roleId);
            List<MenuItem> menuItemList = JSONObject.parseArray(mids, MenuItem.class);
            for (MenuItem menuItem : menuItemList) {
                RoleMenuVO roleMenuVO = new RoleMenuVO();
                roleMenuVO.setRoleId(roleId);
                roleMenuVO.setMenuId(menuItem.getId());
                roleMenuVO.setMenuState(menuItem.getState());
                this.service.insert(roleMenuVO);
            }
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.fail();
        }
    }
}

class MenuItem {

    private Long id;
    private Integer state;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }
}
